/**
 * 文件：framentMain.java
 * 包名：com.ronri.test;
 * 说明：主页(Fragment)
 * 作者：MS During
 * 日期：2017/4/12
 * 历史：
 */
package com.ronri.ams;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.ams.bean.bannerbean;
import com.ronri.common.UrlEncode;
import com.ronri.db.RemoteDataService;
import com.ronri.menuview.JuheGridItem;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class framentMain extends BaseFragment implements AdapterView.OnItemClickListener {

    private Activity activity;

    private RelativeLayout ml1 = null;
    private RelativeLayout ml2 = null;
    private RelativeLayout ml3 = null;
    private RelativeLayout ml4 = null;

    private RelativeLayout mscyrw = null;
    private RelativeLayout mscyhz = null;
    private RelativeLayout mscjjg = null;

    private TextView mcyrw = null;
    private TextView mcyhz = null;
    private TextView mcjjg = null;

    /**
     * 新版界面相关信息：九宫格风格
     */
    private GridView mGridView;
    private List<JuheGridItem> lMenuData = new ArrayList<JuheGridItem>();
    private String IMAGE_ITEM = "imgage_item";
    private String TEXT_ITEM = "text_item";
    private bannerbean mbanner = null;
    private List<String> mBannerList = new ArrayList<>();
    private Context mContext = null;

    // 滚动广告
//    private RollPagerView mRollViewPager = null;
    private Banner banner;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View returnView = inflater.inflate(R.layout.frament_main, container, false);

        mContext = getContext();

        banner= (Banner) returnView.findViewById(R.id.roll_view_pager);
//        mRollViewPager = (RollPagerView) returnView.findViewById(R.id.roll_view_pager);

        getRemoteData();

        ml1 = (RelativeLayout) returnView.findViewById(R.id.l1);
        ml2 = (RelativeLayout) returnView.findViewById(R.id.l2);
        ml3 = (RelativeLayout) returnView.findViewById(R.id.l3);
        ml4 = (RelativeLayout) returnView.findViewById(R.id.l4);
        mscyrw = (RelativeLayout) returnView.findViewById(R.id.scyrw);
        mscyhz = (RelativeLayout) returnView.findViewById(R.id.scyhz);
        mscjjg = (RelativeLayout) returnView.findViewById(R.id.scjjg);

        mcyrw = (TextView)returnView.findViewById(R.id.tvcyrw);
        mcjjg = (TextView)returnView.findViewById(R.id.tvjg);
        mcyhz = (TextView)returnView.findViewById(R.id.tvcyhz);

        mcyrw.setOnClickListener(onClickListener);
        mcyrw.setTag(8);
        mcjjg.setOnClickListener(onClickListener);
        mcjjg.setTag(9);
        mcyhz.setOnClickListener(onClickListener);
        mcyhz.setTag(10);

        ml1.setOnClickListener(onClickListener);
        ml1.setTag(1);
        ml2.setOnClickListener(onClickListener);
        ml2.setTag(2);
        ml3.setOnClickListener(onClickListener);
        ml3.setTag(3);
        ml4.setOnClickListener(onClickListener);
        ml4.setTag(4);

        mscyrw.setOnClickListener(onClickListener);
        mscyrw.setTag(5);
        mscyhz.setOnClickListener(onClickListener);
        mscyhz.setTag(6);
        mscjjg.setOnClickListener(onClickListener);
        mscjjg.setTag(7);

        getCverRemoteData();

        // 9宫格菜单
//        mGridView = (GridView) returnView.findViewById(R.id.juhe_gridview);
//
//        lMenuData.add(new JuheGridItem(R.drawable.cyrw,  "抽样任务",  88, 0x81b7ef));
//        lMenuData.add(new JuheGridItem(R.drawable.cyhz,  "抽样汇总",  200, 0xf7bb45));
//        lMenuData.add(new JuheGridItem(R.drawable.cjjg,  "抽检结果",  3, 0xd96db9));
//        lMenuData.add(new JuheGridItem(R.drawable.cjjg,  "疑问简答",  30, 0x52c5ac));
//
//        JuheGridAdapter saImageItems = new JuheGridAdapter(getContext(), mGridView, lMenuData);
//
//        // 设置GridView的adapter。GridView继承于AbsListView。
//        mGridView.setAdapter(saImageItems);
//        mGridView.setOnItemClickListener(this);

        return returnView;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int nPoint = (int) view.getTag();
            switch (nPoint) {
                case 5:
                case 1: {
                    // 生产主体
                    Intent intent = new Intent(InitApplication.getContext(), com.ronri.ams.task.activity_TaskList.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 0);
                    intent.putExtras(bundle);
                    //跳转Activity
                    startActivityForResult(intent, 1501);
                }
                break;
                case 6:
                case 2: {
                    Intent intent = new Intent(InitApplication.getContext(), com.ronri.ams.task.activity_sample_summray.class);

                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 1);
                    intent.putExtras(bundle);

                    //跳转Activity
                    startActivityForResult(intent, 1502);
                }
                break;
                case 7:
                case 3: {
                    // 生产主体
                    Intent intent = new Intent(InitApplication.getContext(), com.ronri.ams.task.activity_detect_summray.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 2);
                    intent.putExtras(bundle);
                    //跳转Activity
                    startActivityForResult(intent, 1503);
                }
                break;
                case 4: {
//
//                    ToastUtil toastUtil=new ToastUtil(mContext, );
//                    toastUtil.Short(mContext,"正在开发中...")
//                            .setToastBackground(Color.WHITE,R.drawable.toast_radius)
//                            //.setToastColor(Color.WHITE, getResources().getColor(R.color.colorAccent))
//                            .show();
                }
                break;
            }
        }
    };

    /****
     * 获取远程数据
     */
    public void getCverRemoteData() {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getWelcome().getAddress());

        int user_id= InitApplication.LoginInfo.getData().getUser_id();
        String region_code= InitApplication.LoginInfo.getData().getRegion_code();
        Map<String, Object> mParam = new HashMap<String, Object>();
        mParam.put("addFrom", 1);
        mParam.put("addMark", "android");
        mParam.put("user_id", user_id+"");
        mParam.put("region_code", region_code);

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getWelcome().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty())
                            return;

                        try {
                            JSONObject jsonObject = JSON.parseObject(szString);

                            if (jsonObject.getBoolean("success") == true){
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                if(jdata != null)
                                {
                                    mcyrw.setText(jdata.getString("task"));
                                    mcyhz.setText(jdata.getString("pool"));
                                    mcjjg.setText(jdata.getString("result"));
                                }
                            } else {
                                // 提示错误信息
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            //WaitDialog.ShowDialog(mContext, "请稍后...");
                        } else {
                            //WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }


    /****
     * 获取远程数据
     */
    public void getRemoteData() {

        RemoteDataService remoteDataService = new RemoteDataService();

        // 获取远程地址
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getBanner().getAddress());

        Map<String, Object> mParam = new HashMap<String, Object>();

        // 获取远程数据
        remoteDataService.getRemoteData(szRemoteAddress,
                UrlEncode.getUrlParamsByMap(mParam, false),
                InitApplication.SystemConfig.getModule().getTdetail().getMethod(),
                new RemoteDataService.OnRemoteDataEvent() {
                    // 返回结果
                    @Override
                    public void OnResultEvent(String szString) {
                        if (szString.isEmpty())
                            return;

                        try {
                            mbanner = JSON.parseObject(szString, bannerbean.class);

                            if (mbanner.isSuccess()) {
                                for (bannerbean.DataBean iTem : mbanner.getData()) {
                                    mBannerList.add(iTem.getPic());
                                }
//                                //设置播放时间间隔
//                                mRollViewPager.setPlayDelay(5000);
//
//                                //设置透明度
//                                mRollViewPager.setAnimationDurtion(500);
//
//                                //设置适配器
//                                mRollViewPager.setAdapter(new RollNormalAdapter(mBannerList));

                                //设置banner样式
                                banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                                //设置图片加载器
                                banner.setImageLoader(new GlideImageLoader());
                                //设置图片集合
                                banner.setImages(mBannerList);
                                //设置自动轮播，默认为true
                                banner.isAutoPlay(true);
                                //设置轮播时间
                                banner.setDelayTime(3000);
                                //设置指示器位置（当banner模式中有指示器时）
                                banner.setIndicatorGravity(BannerConfig.CENTER);
                                //banner设置方法全部调用完毕时最后调用
                                banner.start();
                            } else {
                                // 提示错误信息
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    // 状态控制，是否显示加载过程
                    @Override
                    public void OnRuningState(int nStatus) {
                        if (nStatus == SystemEnvironmental.StartGetDataFromServer) {
                            //WaitDialog.ShowDialog(mContext, "请稍后...");
                        } else {
                            //WaitDialog.HideDialog();
                        }
                    }

                    @Override
                    public String OnGetCustomParam() {
                        return null;
                    }
                }
        );
    }

    public class GlideImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    }

//    /***
//     * 轮播图片处理
//     */
//    private class RollNormalAdapter extends StaticPagerAdapter {
//
//        private boolean mFromNetwork = false;
//
//        private int[] imgs = {
//                R.drawable.guide2,
//                R.drawable.guide3,
//                R.drawable.guide2
//        };
//
//        private List<String> mLImages = new ArrayList<>();
//
//
//        public RollNormalAdapter(List<String> iTems) {
//            if (iTems.size() > 0) {
//                for (String ii : iTems) {
//                    mLImages.add(ii);
//                }
//
//                mFromNetwork = true;
//            }
//        }
//
//        @Override
//        public View getView(ViewGroup container, int position) {
//            ImageView view = new ImageView(container.getContext());
//
//
//            if (mFromNetwork == true) {
//                new LoadImagesTask(view).execute(mLImages.get(position));
//            } else {
//                view.setImageResource(imgs[position]);
//            }
//
//            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            view.setLayoutParams(
//                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//                            ViewGroup.LayoutParams.MATCH_PARENT));
//            return view;
//        }
//
//
//        @Override
//        public int getCount() {
//            if (mFromNetwork == true) {
//                return mLImages.size();
//            } else {
//                return imgs.length;
//            }
//        }
//    }

    /***
     * 点击后跳转
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (position) {
            case 0: {
                // 生产主体
                Intent intent = new Intent(getContext(), com.ronri.ams.task.activity_TaskList.class);
                Bundle bundle = new Bundle();
                bundle.putInt("type", 0);
                intent.putExtras(bundle);
                //跳转Activity
                startActivityForResult(intent, 1501);
            }
            break;
            case 1: {
                // 生产主体
                Intent intent = new Intent(getContext(), com.ronri.ams.task.activity_sample_summray.class);

                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                intent.putExtras(bundle);

                //跳转Activity
                startActivityForResult(intent, 1502);
            }
            break;
            case 2: {
                // 生产主体
                Intent intent = new Intent(getContext(), com.ronri.ams.task.activity_detect_summray.class);
                Bundle bundle = new Bundle();
                bundle.putInt("type", 2);
                intent.putExtras(bundle);
                //跳转Activity
                startActivityForResult(intent, 1503);
            }
            break;
            default:
                break;
        }

    }
}
